import React, {Component} from 'react'
import {Page} from '../../component/pagination'
import {LayOut} from '../../layout/default_layout'
import {http, renderTitle, queryParse} from '../../common/js/utils'
import MovieCard from './movie_card'
import AdminTable from './admin_table'
import NotFound from '../../component/not_found'
import {connect} from 'react-redux'

function mapStateToProps(state, props) {
  return {
    userInfo: state.get('userInfo')
  }
}

function onShowSizeChange(p, s) {
  this.page = p
  this.size = s
  this.getList(this.props)
}

function setPage() {
  this.page = 1
  this.size = 12
  this.pagination && this.pagination.resetPage()
}

function onSearch(keywords) {
  this.keywords = keywords
  setPage.bind(this)()
  this.getList(this.props)
}

class Home extends Component {

  keywords = ''

  state = {
    placeholder: '搜索',
    keywords: '',
    total: null,
    movieList: []
  }

  getList = props => {
    this.setState({
      placeholder: props.match.params.id || '全部'
    })
    http({
      method: 'get',
      url: `/api/movies/list?size=${this.size}&page=${this.page - 1}&type=${encodeURIComponent(props.match.params.id || '')}&keywords=${encodeURIComponent(this.keywords)}`
    }, window.__LOADING__).then(res => {
      // 当数据总数不为0且当前页码为0时
      if (!res.data.length && res.total > 0) {
        this.page--
        this.refresh()
        this.pagination && this.pagination.resetPage(this.page)
      } else {
        this.setState({
          movieList: res.data,
          total: res.total
        })
      }
    }).catch(() => {
      this.setState({
        movieList: []
      })
    })
  }

  refresh = () => {
    this.getList(this.props)
  }

  componentWillReceiveProps(props) {
    this.layout.clearInput()
    this.keywords = ''
    setPage.bind(this)()
    this.getList(props)
  }

  componentWillMount() {
    const search = queryParse(this.props.location.search)
    if (search.keywords) {
      this.keywords = search.keywords
    }
    renderTitle()
  }

  componentDidMount() {
    setPage.bind(this)()
    this.getList(this.props)
  }

  render() {
    const {total} = this.state
    const {userInfo} = this.props

    return (
      <LayOut placeholder={this.state.placeholder} onSearch={onSearch.bind(this)} onRef={layout => this.layout = layout}>
        <div>
          {
            total === 0
              ? <NotFound text="抱歉，没有相关数据~"/>
              : userInfo.get('role') === 'admin'
                ? <AdminTable refresh={this.refresh} dataSource={this.state.movieList} />
                : <MovieCard movies={this.state.movieList} />
          }
        </div>
        <Page
          ref={el => this.pagination = el}
          className="pagination"
          onChange={onShowSizeChange.bind(this)}
          total={total}
        />
      </LayOut>
    )
  }
}

export default connect(mapStateToProps)(Home)
